package com.leon.alishop.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import com.leon.alishop.core.bo.CityAreaBo;
import com.leon.alishop.core.bof.CityAreaBof;
import com.leon.alishop.core.enumeration.CityAreaTypeEnum;
import com.leon.alishop.core.service.CityAreaService;
import com.leon.alishop.core.vo.CityAreaParams;
import com.leon.alishop.dao.CityAreaDao;
import com.leon.alishop.model.CityArea;

@Controller
@RequestMapping(value = "/cityarea")
public class CityAreaController extends BaseController {

	private static String EDIT_PAGE = "/cityarea/edit";
	
	@RequestMapping(value = "/cityarea-edit")
	public String edit(CityAreaParams vo,
			BindingResult bindingResult, HttpServletRequest req,HttpServletResponse res,Model model){
		if(null == vo)
			vo = new CityAreaParams();
		initModel(model);
		model.addAttribute("params", vo);
		CityAreaBo cityAreaBo = null;
		if(!"edit".equalsIgnoreCase(vo.getReqType())){
			vo.setReqType("edit");
			if(null != vo.getId()){
				cityAreaBo = cityAreaBof.findCityAreaById(vo.getId());
				if(cityAreaBo == null){
					vo.setErrorMsg("未找到该记录！");
				}
			}
			model.addAttribute("cityAreaBo", cityAreaBo);
			return EDIT_PAGE;
		}
		vo.setErrorMsg(checkValidParams(vo));
		if(StringUtils.isNotBlank(vo.getErrorMsg())){
			return EDIT_PAGE;
		}
		int ret = cityAreaService.insertOrUpdateCityAreaMap(vo);
		return EDIT_PAGE;
	}

	private String checkValidParams(CityAreaParams vo){
		if(StringUtils.isBlank(vo.getName())
				|| vo.getName().length()>10){
			return "名称不合法！";
		}
		vo.setName(vo.getName().trim());
		CityAreaTypeEnum type = CityAreaTypeEnum.valueOfOrder(vo.getLevel());
		if(type == null){
			return "类型不合法！";
		}
		CityAreaBo bo;
		if(CityAreaTypeEnum.PROVINCE == type){
			vo.setParentId(Integer.valueOf(0));
		}else{
			bo = cityAreaBof.findCityAreaById(vo.getParentId());
			if(bo == null){
				return "上级地区不存在不合法！";
			}
		}
		bo = cityAreaBof.findCityAreaByName(vo.getName());
		if(bo!= null && bo.getParentId().equals(vo.getParentId())){
			return "该区域名称已经存在！";
		}
		return null;
	}
	
	private void initModel(Model model) {
		model.addAttribute("cityAreaTypeEnums", CityAreaTypeEnum.values());
		model.addAttribute("cityAreaList", cityAreaBof.findAllCityArea());
	}
	
	@Autowired
	private CityAreaBof cityAreaBof;
	
	@Autowired
	private CityAreaService cityAreaService;
	
}
